package org.pku_uestc.hackathon.sensor;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;
import org.pku_uestc.hackathon.bean.ISensorHandler;
import org.pku_uestc.hackathon.bean.Sensor;

import android.annotation.SuppressLint;
import android.os.Handler;
import android.os.Message;

@SuppressLint("HandlerLeak")
public class TemperatureSensor extends Sensor {

	private int id;
	
	public TemperatureSensor(int id){
		super();
		this.id = id;
	}
	
	@Override
	public int getType() {
		// TODO Auto-generated method stub
		return TYPE_TEMPERATURE;
	}
	
    @SuppressLint("HandlerLeak")
	private final Handler checkHandler = new Handler(){
    	@Override
		public void handleMessage(Message msg){
    		JSONTokener jsonParser = new JSONTokener(msg.getData().getString("RESPONSE"));  
			try {
				JSONObject data = (JSONObject) jsonParser.nextValue();
				//JSONObject th_sensor = data.getJSONObject("th_sensor");
				JSONArray data_points = data.getJSONArray("temperature_data_points");
				if(data_points.length()>0){
					String lastvalue = ((JSONObject)data_points.get(0)).getString("value");
					if(list != null)
						for(ISensorHandler handler : list)
							handler.check(lastvalue);
				}
			} catch (JSONException e) {
				// TODO Auto-generated catch block
	 			e.printStackTrace();
			}  
    	}
    };
    
    @Override
    public void request(int timer) {
    	this.preformGetRequest(checkHandler, 
    			"http://www-staging.huantengsmart.com/temperature_data/"+id+".json"
    	             +"?start=15_min_ago&auth_token="+token);
    }
    
    @Override
	public int getId() {
		// TODO Auto-generated method stub
		return id;
	}
}
